﻿namespace Chapter02.DesginModeBcl {
    public class WeatherData : IObservable<WeatherInfo> {
        private readonly HashSet<IObserver<WeatherInfo>> observers = [];
        private readonly HashSet<WeatherInfo> weathers = [];

        public IDisposable Subscribe(IObserver<WeatherInfo> observer) {
            observers.Add(observer);
            return new Unsubscriber(observers, observer);
        }

        public void SetStatus(WeatherInfo info) {
            foreach (var observer in observers) {
                observer.OnNext(info);
            }
        }

        private class Unsubscriber(HashSet<IObserver<WeatherInfo>> observers, IObserver<WeatherInfo> observer)
            : IDisposable {

            private readonly HashSet<IObserver<WeatherInfo>> observers = observers;
            private readonly IObserver<WeatherInfo> observer = observer;

            public void Dispose() {
                observers.Remove(observer);
            }
        }
    }
}
